
package com.mutual.commom.util;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * User: Ren yulin
 * Date: 13-1-17 上午9:44
 */
public class JSONUtil {
    public static Logger logger = Logger.getLogger(JSONUtil.class);

    public static List getListFromPageJSON(String jsonStr) {
        if (jsonStr == null || "".equals(jsonStr)) {
            logger.debug("pages 式的 json串为空");
            return null;
        }
        int begin = jsonStr.indexOf("rows\":[");
        if (begin == -1) {
            logger.debug("json串不是约定的page式");
            return null;
        }
        String str = jsonStr.substring(begin + "\"rows\":".length() - 1, jsonStr.length() - 1);
        try {
            return JSONUtil.getListFormJSON(str);
        } catch (Exception e) {
            logger.debug("json串不是约定的page式");
            logger.error("JSONUtil   getListFromPageJSON方法出错，异常信息为:",e);  
        }
        return null;
    }
    
    /**
     * JSON转MAP
     * @param jsonStr
     * @return
     */
//    public static Map<String, Object> parseJSON2Map(String jsonStr){
//		Map<String, Object> map = new HashMap<String, Object>();
//		//最外层解析
//		JSONObject json = JSONObject.fromObject(jsonStr);
//		for(Object k : json.keySet()){
//			Object v = json.get(k); 
//			//如果内层还是数组的话，继续解析
//			if(v instanceof JSONArray){
//				List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
//				Iterator<JSONObject> it = ((JSONArray)v).iterator();
//				while(it.hasNext()){
//					JSONObject json2 = it.next();
//					list.add(parseJSON2Map(json2.toString()));
//				}
//				map.put(k.toString(), list);
//			} else {
//				map.put(k.toString(), v);
//			}
//		}
//		return map;
//	}

    /**
     * 将[{}]式的JSON串转换为List
     *
     * @param jsonStr
     * @return
     */
    public static List getListFormJSON(String jsonStr) {
        return JSON.parseArray(jsonStr);
    }

    /**
     * 将普通对象转换为JSON串
     *
     * @param obj
     * @return
     */
    public static String getJSONFromObj(Object obj) {
        return JSON.toJSONString(obj);
    }

    /**
     * 将对象集合转换为JSON串
     *
     * @param list
     * @return
     */
    public static String getJSONFromObjList(List list) {
        return JSON.toJSONString(list);
    }

    /**
     * 将PAGE对象转换为JSON
     *
     * @param pages
     * @return
     */
    /*public static String getJSONFromPage(Page pages) {
        StringBuilder builder = new StringBuilder("{\"total\":" + pages.getTotalRow() + ",\"totalPage\":" + pages.getTotalPage() + ",\n\"rows\":[");
        int index = 0;
        for (Object obj : pages.getList()) {
            if (obj instanceof Model) {
                Model model = (Model) obj;
                builder.append(model.toJson());
            } else if (obj instanceof Record) {
                Record record = (Record) obj;
                builder.append(record.toJson());
            }
            index++;
            if (index < pages.getList().size()) {
                builder.append(",");
            }
        }
        builder.append("]\n}");
        return builder.toString();
    }*/

    /**
     * 将LIST对象转换为JSON
     *
     * @param list
     * @return
     */
    /*public static String getJSONFromList(List list) {
        StringBuilder builder = new StringBuilder("[");
        int index = 0;
        for (Object obj : list) {
            if (obj instanceof Model) {
                Model model = (Model) obj;
                builder.append(model.toJson());
            } else if (obj instanceof Record) {
                Record record = (Record) obj;
                builder.append(record.toJson());
            }
            index++;
            if (index < list.size()) {
                builder.append(",");
            }
        }
        builder.append("]");
        return builder.toString();
    }*/


    /**
     * 将MAP转换为JSON
     *
     * @param map
     * @return
     */
    public static String getJSONFromMap(Map map) {
        if (map == null) {
            return null;
        }
        return JSON.toJSONString(map);
    }

    public static Map getMapFromJSON(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return JSON.parseObject(str);
    }

    private static String getJSON(Object obj, StringBuilder builder) {
        List list = (List) obj;
        int i = 0;
        for (Object listObj : list) {
            builder.append(JSON.toJSONString(listObj));
            if (i < list.size() - 1) {
                builder.append(",");
            }
            i++;
        }
        return builder.toString();
    }
    
    public static <T> T parseJsonToEntity(String jsonStr,Class<T> entityCalss){
    	T entity = null;
		try {
			entity = JSON.parseObject(jsonStr,entityCalss);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
    }

    
    public static <T> List<T> parseJsonToList(String jsonStr,Class<T> entityCalss){
    	List<T> list = new ArrayList<>();
		try {
			list = JSON.parseArray(jsonStr, entityCalss);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
    }
}
